﻿using System.IO;
using System.Reflection;

namespace GurLoaderWPF.Test
{
    public class ResourceLoader
    {
        public static string GetResourceText( string resourceName )
        {
            string result = string.Empty;

            Assembly asm = Assembly.GetExecutingAssembly();

            string resourcePath = GetResourcePath(asm, resourceName);
            using ( Stream resourceStream = GetResourceStreamInternal( resourcePath ) )
            {
                using ( StreamReader streamReader = new StreamReader( resourceStream ) )
                {
                    result = streamReader.ReadToEnd();
                }
            }

            return result;
        }

        private static string GetResourcePath(Assembly asm, string resourceName)
        {
            return string.Format("{0}.{1}", asm.GetName().Name, resourceName.Replace("/", "."));
        }

        public static byte[] GetResourceBytes( string resourceName )
        {
            byte[] result = null;

            Assembly asm  = Assembly.GetExecutingAssembly();

            string resourcePath = GetResourcePath(asm, resourceName);
            using ( Stream resourceStream = GetResourceStreamInternal( resourcePath ) )
            {
                using ( MemoryStream outputStream = new MemoryStream() )
                {
                    resourceStream.CopyTo(outputStream);
                    result = outputStream.ToArray();
                }
            }

            return result;
        }

        private static Stream GetResourceStreamInternal( string resourceName )
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            return asm.GetManifestResourceStream(resourceName);
        }
    }
}
